package com.yzg.simple.netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;

/**
 *
 * 自定义hander 处理器 采
 *
 * 1.用Http请求.得到HttpObject 对象
 *
 * 2.SimpleChannelInboundHandler 是ChannelInboundHandlerAdapter 的子类,封装了好多已经实现的方法
 *
 *
 */
public class HettyHttpHander extends SimpleChannelInboundHandler<HttpObject>{
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {

        //类型转换
        if (msg instanceof HttpRequest){

            HttpRequest request = (HttpRequest) msg;

            //浏览器访问,会得到/favicon.ico 不可避免,所以我们资源拦截
            URI uri =  URI.create(request.uri());
            if ("/favicon.ico".equals(uri.getPath())){
                System.out.println(uri.getPath());
                return;
            }

            //像浏览器写出数据
            String json = "{\"张三\":\"李四\"}";
            ByteBuf byteBuf = Unpooled.copiedBuffer(json, CharsetUtil.UTF_8);
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,byteBuf);
            //设置头信息
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH,byteBuf.readableBytes());
            response.headers().set(HttpHeaderNames.CONTENT_TYPE,"application/json");
            ctx.writeAndFlush(response);
        }

    }
}
